import store from '@/store'

export function getDeviceUUID() {
    let deviceId = uni.getStorageSync('uni_deviceId') ||
        uni.getSystemInfoSync().deviceId ||
        uni.getSystemInfoSync().system + '_' + Math.random().toString(36).substr(2);

    uni.setStorageSync('uni_deviceId', deviceId)
    return deviceId;
}

function image2Base64(imgSrc) {
    return new Promise(function (resolve, reject) {
        let img = new Image();
        img.src = imgSrc;
        img.onload = function () {
            const canvas = document.createElement("canvas");
            const maxSidelen = 100
            if (img.width >= img.height && img.width > maxSidelen) {
                canvas.width = maxSidelen;
                canvas.height = img.height / img.width * maxSidelen;
            } else if (img.height > img.width && img.height > maxSidelen) {
                canvas.width = img.width / img.height * maxSidelen;
                canvas.height = maxSidelen;
            } else {
                canvas.width = img.width;
                canvas.height = img.height;
            }
            const ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
            const dataURL = canvas.toDataURL("image/png");
            resolve(dataURL)
        }
    })
}

// 封装一层请求，请求前增加拦截器，用于添加token，刷新token，封装调用
function request(object) {
    uni.addInterceptor('request', {
        invoke(args) {
            args.header = { 'token': uni.getStorageSync('uni_id_token') }
        }
    })

    return new Promise(function (resolve, reject) {
        uni.request(object).then(data => {
            const [err, res] = data
            if (res) {
                if (res.data.success) {
                    resolve(res.data.result)
                } else {
                    // token超时直接重新获取token，再次请求
                    const errStr = res.data.message ?? res.data.Message
                    if (errStr === 'token异常' || errStr === '请求token超时') {
                        resetToken()
                            .then(() => {
                                request(object).then(res => resolve(res)).catch(err => reject(err))
                            })
                            .catch(() => {
                                uni.reLaunch({ url: '../pages/login/login' })
                            })
                    } else {
                        reject(errStr)
                    }
                }
            } else {
                reject(err)
            }
        }).catch(err => {
            reject(err)
        })
    })
}

// 校验token
function checkToken(token) {
    return new Promise(function (resolve, reject) {
        const uniIdToken = token ? token : uni.getStorageSync('uni_id_token')
        uni.request({
            url: store.state.domainUrl + '/api/userinfo/checkToken',
            method: 'post',
            data: '"' + uniIdToken + '"'
        }).then(data => {
            const [err, res] = data
            if (res) {
                if (res.data.success) {
                    resolve()
                } else {
                    resetToken().then(() => resolve()).catch(() => reject(res.data.message))
                }
            } else {
                resetToken().then(() => resolve()).catch(() => reject('身份验证失败'))
            }
        }).catch(() => resetToken().then(() => resolve()).catch(() => reject('身份验证失败')))
    })
}

// token异常时，根据登录记录重新获取token
function resetToken() {
    return new Promise(function (resolve, reject) {
        const accountInfo = uni.getStorageSync('accountInfo')
        if (accountInfo) {
            uni.request({
                url: store.state.domainUrl + '/api/userInfo/login',
                method: 'post',
                data: accountInfo
            }).then(data => {
                const [err, res] = data
                if (res && res.data.success) {
                    res.data.result.userInfo.id = undefined
                    uni.setStorageSync('uni_id_token', res.data.result.token)
                    uni.setStorageSync('username', res.data.result.userInfo.userName)
                    uni.setStorageSync('userInfo', res.data.result.userInfo)
                    uni.setStorageSync('login_type', 'online')
                    uni.setStorageSync('uni_id_has_pwd', true)
                    resolve()
                } else {
                    reject('身份验证失败')
                }
            }).catch(() => { reject('身份验证失败') })
        } else { reject('身份验证失败') }
    })
}

export { request, checkToken, resetToken, image2Base64 }
